import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { baseUrl } from '@/setting';
import { notification } from 'ant-design-vue';
import { getToken, getUserFactory, logout } from '@/utils/user-util';
import { ResponseBody } from '@/api/typing';

export const REQUEST_TOKEN_KEY = 'Access-Token';
export const REQUEST_FACTORY_KEY = 'Factory-Code';

const service = axios.create({
  baseURL: baseUrl,
  timeout: 70000,
  withCredentials: false,
  headers: { 'X-Requested-With': 'XMLHttpRequest' }
});

// 异常拦截处理器
const errorHandler = (error: AxiosError): Promise<any> => {
  if (error.response) {
    const { data = {}, status, statusText } = error.response;
    // 403 无权限
    if (status === 403) {
      notification.error({
        message: '禁止访问',
        description: (data && data.message) || statusText,
      });
    }
    // 401 未登录/未授权
    if (status === 401 && data.result && data.result.isLogin) {
      notification.error({
        message: '未授权',
        description: '授权验证失败',
      });
    }
  }
  return Promise.reject(error);
};

// 请求拦截器
const requestHandler = (
  config: AxiosRequestConfig,
): AxiosRequestConfig | Promise<AxiosRequestConfig> => {
  const token = getToken();
  if (token) {
    config.headers[REQUEST_TOKEN_KEY] = token;
    const userFactory = getUserFactory();
    if (userFactory) {
      config.headers[REQUEST_FACTORY_KEY] = userFactory;
    }
  }
  return config;
};

// 响应拦截器
const responseHandler = (
  response: AxiosResponse,
): ResponseBody | AxiosResponse | Promise<any> | any => {
  const { data: { status, unknown, message } } = response;
  if (status === 401) {
    // 清空token
    logout();
    window.location.href = ''
    //notification.warning({  message: '警告', description: '未授权，服务器拒绝请求', duration: 2, });
    //setTimeout(() => window.location.reload(), 2000);
  } else if (status === 500 && !unknown) {
    notification.warning({ message: '警告', description: message, duration: 4, });
  } else if (status === 500 && unknown) {
    console.info('运行时异常信息：', message)
    notification.error({ message: '错误', description: '服务器未知错误', duration: 4, });
  }
  return response.data;
};
service.interceptors.request.use(requestHandler, errorHandler);
service.interceptors.response.use(responseHandler, errorHandler);

export default service;

